<template>
  <div>
    <el-dialog :model-value="visible" title="添加字典" width="30%" :close-on-click-modal="false" @close="close">
      <el-form :rules="rules" :model="dict" ref="addForm">
        <el-form-item label="编码: " prop="code">
          <el-input v-model="dict.code" placeholder="请输入编码"></el-input>
        </el-form-item>
        <el-form-item label="名称: " prop="name">
          <el-input v-model="dict.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="排序: ">
          <el-input-number v-model="dict.sorts"/>
        </el-form-item>
      </el-form>

      <div style="text-align: center; ">
        <el-button type="primary" @click="saveDict">保存</el-button>
        <el-button type="info" @click="close">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup> 
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { save, updateDict } from "@/api/dict.js";
//声明同名引用
const addForm = ref();
//声明事件  需要父组件监听
const emits = defineEmits(["close","refreshDate"]);
//定义属性
const props = defineProps({
  visible: {
    type: Boolean,
    default: true //默认显示
  }
});
//表单数据
const dict = ref({
  code: "",
  name: "",
  pid: 0,
  sorts: 0
})
//验证规则
const rules = {
  code: [{ required: true, message: "请输入编码", trigger: "blur" }],
  name: [{ required: true, message: "请输入名称", trigger: "blur" }]
};
//关闭对话窗回调
function close() {
  //触发关闭事件
  emits("close");
}

function init(pid, row) {
  if (row) {
    //编辑
    dict.value = row;
  } else {
    //新增
    dict.value = {
      code: "",
      name: "",
      pid: pid,
      sorts: 0
    };
  }
}
//保存
async function saveDict() {
  let valid = await addForm.value.validate(() => { });
  if (!valid) return;
  let res;
  if (dict.value.id) {
      //说明修改
    res = await updateDict(dict.value);
  } else {
    //说明新增
    res = await save(dict.value);
  }
  if (res.code == 200) {
    ElMessage({
      message: "保存成功",
      type: "success"
    });
    //关闭前通知父组件刷新数据
    emits("refreshDate");
    close();
  }
}
//暴露方法 供父组件使用
defineExpose({ init });
</script>

<style scoped>

</style>
